package com.example.userserver.utils;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import java.util.*;


/**
 * bean 操作工具类
 *
 */
public class BeanCopyUtils {


    /**
     * bean 复制
     *
     * @param source
     * @param classType
     * @param <T>
     * @return
     */
    public static <T> T copyProperties(Object source, Class<T> classType) {
        try {
            T t = classType.newInstance();
            BeanUtils.copyProperties(source, t);
            return t;
        } catch (Exception e) {
            throw new RuntimeException("对象转换异常", e);
        }
    }

    /**
     * bean 复制忽略空
     *
     * @param source
     * @param target
     */
    public static void copyPropertiesIgnoreNull(Object source, Object target) {
        if (null != source) {
            BeanUtils.copyProperties(source, target, getNullPropertyNames(source));
        }
    }

    private static String[] getNullPropertyNames(Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<>();
        for (java.beans.PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null) {
                emptyNames.add(pd.getName());
            }
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }



}
